package org.jfonia.connect5.gui;

import java.awt.event.FocusEvent;
import org.jfonia.connect5.basics.BasicValueNode;
import org.jfonia.connect5.basics.MutableValueNode;
import org.jfonia.connect5.basics.Observer;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.event.FocusAdapter;
import javax.swing.JTextField;
import org.jfonia.connect5.basics.Node;

/**
 * @author wijnand.schepens@hogent.be
 */
public class MyTextField extends JTextField
{

	private MutableValueNode<Integer> xNode = new BasicValueNode<Integer>(0);
	private MutableValueNode<Integer> yNode = new BasicValueNode<Integer>(0);

	public MyTextField(String text)
	{
		super(text);

		setSize(getPreferredSize());
		
		xNode.addObserver(new Observer()
		{

			public void onNotify(Object source)
			{
				MyTextField.super.setLocation(xNode.getValue(), getY());
			}
		});
		yNode.addObserver(new Observer()
		{

			public void onNotify(Object source)
			{
				MyTextField.super.setLocation(getX(), yNode.getValue());
			}
		});

		this.addFocusListener(new FocusAdapter() {
			public void focusLost(FocusEvent e)
			{
				updateWidth();
			}
		});


		updateWidth();
//
//		this.addPropertyChangeListener(new PropertyChangeListener() {
//
//			public void propertyChange(PropertyChangeEvent evt)
//			{
//				System.out.println("Property change " + evt.getPropertyName() + ": from " +evt.getOldValue() + " to " + evt.getNewValue());
//			}
//		});
//
//		this.addPropertyChangeListener("text", new PropertyChangeListener() {
//
//			public void propertyChange(PropertyChangeEvent evt)
//			{
//				System.out.println("Property text changed " + evt.getPropertyName());
//			}
//		});
	}

	@Override
	public void setLocation(int x, int y)
	{
		xNode.setValue(x);
		//yNode.setValue(y);
	}

	@Override
	public void setLocation(Point p)
	{
		setLocation(p.x, p.y);
	}

	void updateWidth()
	{
		//setSize(getText().length()*15, getHeight());  // TODO...
		Dimension d = getPreferredSize();
		setSize(d.width + 10, d.height);
	}

	public MutableValueNode<Integer> getXNode()
	{
		return xNode;
	}

	public MutableValueNode<Integer> getYNode()
	{
		return yNode;
	}

	
}
